package com.supor.aiot.home.ui.device.config;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.callback.OnItemClickListener;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.supor.aiot.common.analysis.event.BindFailureEvent;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.helper.ConfigActivityManager;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.NFCHelper;
import com.supor.aiot.common.helper.WifiStationManager;
import com.supor.aiot.home.R;
import com.supor.aiot.home.bean.PingResult;
import com.supor.aiot.home.databinding.ActivityWifiConfigBinding;
import com.supor.aiot.home.helper.APHelper;
import com.supor.aiot.home.helper.DataCache;
import com.supor.aiot.home.utils.PopUtils;
import com.supor.nfc.lib.utils.NfcUtils;

import androidx.annotation.Nullable;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: WiFi配网页，包含NFC和AP配网 <br>
 * 作者: lei <br>
 * 日期: 2020/12/6 <br>
 */
public class WifiConfigActivity extends BaseConfigActivity<NoViewModel, ActivityWifiConfigBinding> implements WiFiConfigPresenter.ConfigView {
    private Handler handler;
    private WiFiConfigPresenter presenter;
    private String countdownTip;
    private Bundle bundle;
    private int step1Type = -1;
    private boolean wantJumpSelectPage = false;
    private String mac;
    private PingResult pingResult;
    /**
     * step1是否成功，用于AP配网检测网络
     */
    private boolean ifStep1Finish = false;
    /**
     * step11为新增网络检测步骤
     */
    private boolean ifStartStep11 = false;
    /**
     * 绑定类型：0-NFC|1-AP|2-NFC AP
     */
    private int configType = 0;
    private String routerSsid;
    private String routerBssid;
    private String routerPwd;
    private ProductType.ProductModel productModel;
    private WifiConfigContainer configContainer;
    public static boolean hasStepTwo = false;

    @Override
    protected int resourceId() {
        return R.layout.activity_wifi_config;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.configNfc(this);
            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent,
                    null, null);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        NfcUtils.init(this);
        PopUtils.getInstance().initNFCPop(this);
    }

    public void initView() {
        bindingView.setViewM(this);
        handler = new Handler();
        presenter = new WiFiConfigPresenter(this, this);
        boolean isApMode = WifiStationManager.isWifiApOpen(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> showDialog());
        bindingView.toolbar.setTvLeftOnClickListener(v -> showDialog());
        countdownTip = getString(R.string.bind_step2_countdown);
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
                return;
            }
            bundle = intent.getExtras();
            if (bundle != null) {
                configType = bundle.getInt(Constants.Key.CONFIG_TYPE, 0);
                routerSsid = bundle.getString(Constants.Key.SSID);
                routerBssid = bundle.getString(Constants.Key.BSSID);
                routerPwd = bundle.getString(Constants.Key.PASS);
            }
        } else {
            finish();
            return;
        }
        bindingView.toolbar.setLeftText((configType == 2) ? getString(R.string.config_nfc_ap_title) :
                (configType == 0 ? getString(R.string.config_nfc_title) :
                        getString(R.string.bind_net_guide)));
        bindingView.configTop.setConfig1Text((configType == 2) ? getString(R.string.ap_settings) :
                getString(R.string.bind_config_tip1));
        bindingView.configTop.setConfig2Text(configType == 0 ? getString(R.string.nfc_touch) :
                        getString(R.string.top_start_ap));
        bindingView.llRetry.setVisibility(configType == 0 ? View.VISIBLE : View.GONE);

        configContainer = new WifiConfigContainer(this, bindingView.llConfig);
        configContainer.setClickListener(retryClickListener);
        configContainer.setProductModel(productModel);
        configContainer.addItem();

        presenter.init(bundle, productModel);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcUtils.mNfcAdapter == null) {
            NfcUtils.init(this);
            NfcUtils.configNfc(this);
        }
        if (!PopUtils.getInstance().isNFCPopShow()) {
            return;
        }
        String gizIp = "";
        if (!TextUtils.isEmpty(DataCache.GIZ_IP)) {
            gizIp = DataCache.GIZ_IP;
            // DataCache.GIZ_IP = BaseSharedPreferences.getString(this, Constants.Key.GIZ_IP);
        }
        RecordBean recordBean = NFCHelper.getInstance().processIntent(intent);
        if (NFCHelper.getInstance().processRecord(this, intent, recordBean,
                gizIp, routerSsid, routerPwd, routerBssid)) {
            DataCache.CONFIG_START_TIME = System.currentTimeMillis();
            PopUtils.getInstance().touchSuccess();
            bindingView.btnNextStep.setEnabled(false);
            setProductModel(recordBean);
            new Handler().postDelayed(() -> continueAddDevice(recordBean), 1700);
        } else {
            PopUtils.getInstance().dismissNFCPop();
        }
    }

    private void continueAddDevice(RecordBean recordBean) {
        presenter.setStopConfig(false);
        configContainer.addItem();
        presenter.config(recordBean);
    }

    private void setProductModel(RecordBean recordBean) {
        if (!TextUtils.isEmpty(recordBean.getProductId())) {
            for (ProductType productType : GlobalDataCache.productTypeList) {
                if (productType.Children != null) {
                    for (ProductType.ProductModel child : productType.Children) {
                        if (!TextUtils.isEmpty(recordBean.getProductId())
                                && recordBean.getProductId().equalsIgnoreCase(child.productId)) {
                            configContainer.setProductModel(child);
                            return;
                        }
                    }
                }
            }
        }
        configContainer.setProductModel(null);
    }

    /**
     * 显示是否放弃添加产品对话框
     */
    private void showDialog() {
        presenter.showDialog(getString(R.string.bind_give_up_add_msg), null, (dialog, which) -> {
            String currentWifiSSID = WifiStationManager.getInstance().getCurrentWifiSSID();
            if (currentWifiSSID != null && currentWifiSSID.startsWith(Constants.SUPOR_AP_PREFIX)) {
                WifiStationManager.getInstance().disconnectWifi();
            }
            ConfigActivityManager.removeActivity(WifiConfigActivity.this);
            ConfigActivityManager.finishAll();
            presenter.analysisBindFailure(BindFailureEvent.Value.REASON_ABANDON);
            finish();
        }, (dialog, which) -> {
            presenter.closeDialog();
            if (wantJumpSelectPage && step1Type != -1) {
                jumpSelectWiFi(step1Type);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (configContainer.isDialogShow()) {
            configContainer.hideDialog();
            return;
        }
        showDialog();
    }

    public void onViewClicked(View view) {
        if (view.getId() == R.id.btn_next_step) {
            // setResult(1);
            // finish();
            new Handler().postDelayed(() -> finishAllConfig(false), 300);
        } else if (view.getId() == R.id.tv_retry) {
            if (bindingView.btnNextStep.isEnabled()) {
                PopUtils.getInstance().showNFCPop(this, bindingView.clRoot);
            } else {
                ToastUtils.getInstance().showCustomToast("设备正在配网中");
            }
        }
    }

    private void finishAllConfig(boolean retry) {
        ConfigActivityManager.removeActivity(WifiConfigActivity.this);
        ConfigActivityManager.finishAll();
        if (retry) {
            startActivity(new Intent(this, NetGuideActivity.class));
        }
        finish();
    }

    @Override
    public void countdown(int count) {
        configContainer.countdown(count);
        // bindingView.tvStep2Countdown.setText(String.format(countdownTip, count));
    }

    @Override
    public void updateNetStatus(int type) {
        super.updateNetStatus(type);
        Logc.i("connect type: " + type);
        if (type == 1) {
            checkNet();
        } else if (type == 4) {
            handler.postDelayed(() -> {
                if (ifStep1Finish) {
                    ifStep1Finish = false;
                    presenter.checkNetAvailable();
                }
            }, 5000);
        }
    }

    private synchronized void checkNet() {
        String currentWifiSSID = WifiStationManager.getInstance().getCurrentWifiSSID();
        Logc.i("current SSID: " + currentWifiSSID);
        if (currentWifiSSID != null && !currentWifiSSID.startsWith(Constants.SUPOR_AP_PREFIX)) {
            if (ifStep1Finish) {
                ifStep1Finish = false;
                handler.removeCallbacksAndMessages(null);
                presenter.checkNetAvailable();
            }
        }
    }

    @Override
    public void onStep1(APHelper.Step result) {
        runOnUiThread(() -> {
            Logc.i("onStep1: mac: " + mac);
            configContainer.onStep1(result);
            switch (result) {
                case SUCCESS:
                    if (hasStepTwo) {
                        if (configType == 0) {
                            presenter.checkNetAvailable();
                        } else {
                            ifStep1Finish = true;
                        }
                    } else {
                        ifStartStep11 = true;
                        presenter.queryStatus(mac);
                        presenter.startTimer();
                    }

                    break;
                case FAILURE:
                    bindingView.btnNextStep.setEnabled(true);
                    presenter.pushBindResult("", "0");
                    break;
                case NO_FOUND_AP:
                case CONN_AP_FAILURE:
                case MULTI_AP:
                case CONN_ROUTER_FAILURE:
                    step1Type = result.ordinal();
                    jumpSelectWiFi(step1Type);
                    break;
                default:
                    break;
            }
        });
    }

    private void jumpSelectWiFi(int type) {
        if (!presenter.isDialogShow()) {
            Intent intent = new Intent(this, SelectWifiActivity.class);
            intent.putExtra(Constants.Key.param_type, type);
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            startActivityForResult(intent, Constants.REQUEST_CODE);
            wantJumpSelectPage = false;
        } else {
            wantJumpSelectPage = true;
        }
    }

    @Override
    public void onStep2(int result, PingResult pingResult) {
        runOnUiThread(() -> {
            configContainer.onStep2(result, pingResult, ifStartStep11);
            if (result == 0) {
                ifStartStep11 = true;
                presenter.queryStatus(mac);
                presenter.startTimer();
            } else {
                this.pingResult = pingResult;
                if ("100%".equalsIgnoreCase(pingResult.loss) || !ifStartStep11) {

                    showStep11Error();

                    bindingView.btnNextStep.setEnabled(true);
                    presenter.pushBindResult(this.mac, "0");
                }
            }
        });
    }

    /**
     * 显示网络检测错误原因，目前丢包率为100%和0都会显示网络检测错误
     */
    private void showStep11Error() {
        // int netSpeed = NetSpeedUtils.getRxNetSpeed(this);
        // if (pingResult != null && TextUtils.isEmpty(pingResult.loss)) {
        //     int loss = Integer.parseInt(pingResult.loss.replace("%", ""));
        //     if (loss == 100 || loss == 0) {
        //         bindingView.etvErrorMsg12.setText(String.format(getString(R.string.bind_step2_error_msg2),
        //                 this.mac));
        //     } else {
        //         int avgRtt = Integer.parseInt(pingResult.avgRtt);
        //         bindingView.etvErrorMsg12.setText(String.format(getString(R.string.bind_step2_error_msg1),
        //                 this.mac, pingResult.loss, (avgRtt + "ms")));
        //     }
        //     return;
        // }
        // WifiInfo wifiInfo = WifiStationManager.getInstance().getConnectionWifiInfo();
        // if (wifiInfo != null) {
        //     int rssi = wifiInfo.getRssi();
        //     if (rssi >= -100 && rssi <= -76) {
        //         bindingView.etvErrorMsg12.setText(String.format(getString(R.string.bind_step2_error_msg3),
        //                 this.mac, (rssi + "dBm")));
        //         return;
        //     }
        //
        // }
        // bindingView.etvErrorMsg12.setText(String.format(getString(R.string.bind_step2_error_msg2),
        //         this.mac));
    }

    @Override
    public void onStep3(String bindData) {
        runOnUiThread(() -> {
            configContainer.onStep3(bindData);
            bindingView.btnNextStep.setEnabled(true);
            if (bindData != null) {
                bindingView.configTop.setLineLeft3Color(R.color.colorPrimary);
                bindingView.configTop.setConfig3TextColor(getResources().getColor(R.color.content_default));
                bindingView.configTop.setConfig3Drawable(R.drawable.bg_primary_thumb);

                presenter.stopTimer();
                presenter.pushBindResult(this.mac, "1");
                // SuporPresenter.getInstance().reportConfigNetworkStatus(bindData);

            } else {
                // onMac(this.mac);
                presenter.setStopConfig(true);
                presenter.pushBindResult(this.mac, "0");
            }
        });
    }

    @Override
    public void onCloseAccount() {
        BaseSharedPreferences.setString(AppAgent.getApp(),
                Constants.Key.param_saveInfo, "");
        presenter.stopTimer();
        new Handler().postDelayed(() -> finishAllConfig(false), 100);
        // SuporPresenter.getInstance().reportCloseAccount(1);
    }

    @Override
    public void onMac(String mac) {
        Logc.e("onMac: mac: " + mac);
        if (mac != null) {
            this.mac = mac.toUpperCase();
        }
        configContainer.onMac(mac);
    }

    private OnItemClickListener retryClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (view.getId() == R.id.tv_check_reason) {
                setResult(1);
                finish();
            }
        }

        @Override
        public boolean onItemLongClick(View view, int position) {
            return false;
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE) {
            if (resultCode == 0) {
                presenter.init(bundle, productModel);
            } else if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
        NfcUtils.mNfcAdapter = null;
        PopUtils.getInstance().dismissNFCPop();
    }
}
